All files / web/src/app/api/flowchart-workshop/sessions/[id]/versions route.ts

0% Statements 0/128
0% Branches 0/1
0% Functions 0/1
0% Lines 0/128

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129                                                                                                                                                                                                                                                                 
/**
 * Version History API for Flowchart Workshop
 *
 * GET /api/flowchart-workshop/sessions/[id]/versions
 * - Returns all versions for the session, ordered by version number DESC
 *
 * POST /api/flowchart-workshop/sessions/[id]/versions
 * - Restore a specific version by copying its data into the current draft
 * - Body: { versionNumber: number }
 */

import { and, desc, eq } from 'drizzle-orm'
import { NextResponse } from 'next/server'
import { withAuth } from '@/lib/auth/withAuth'
import { db, schema } from '@/db'
import { getUserId } from '@/lib/viewer'

/**
 * GET /api/flowchart-workshop/sessions/[id]/versions
 * List all versions for the session
 *
 * Returns: { versions: FlowchartVersionHistory[], currentVersion: number }
 */
export const GET = withAuth(async (_request, { params }) => {
  try {
    const { id } = (await params) as { id: string }
    const userId = await getUserId()

    // Verify session ownership
    const session = await db.query.workshopSessions.findFirst({
      where: and(eq(schema.workshopSessions.id, id), eq(schema.workshopSessions.userId, userId)),
    })

    if (!session) {
      return NextResponse.json({ error: 'Session not found' }, { status: 404 })
    }

    // Get all versions for this session
    const versions = await db.query.flowchartVersionHistory.findMany({
      where: eq(schema.flowchartVersionHistory.sessionId, id),
      orderBy: [desc(schema.flowchartVersionHistory.versionNumber)],
    })

    // Add isCurrent flag to each version
    const currentVersion = session.currentVersionNumber ?? 0
    const versionsWithCurrent = versions.map((v) => ({
      ...v,
      isCurrent: v.versionNumber === currentVersion,
    }))

    return NextResponse.json({
      versions: versionsWithCurrent,
      currentVersion,
    })
  } catch (error) {
    console.error('Failed to fetch version history:', error)
    return NextResponse.json({ error: 'Failed to fetch versions' }, { status: 500 })
  }
})

/**
 * POST /api/flowchart-workshop/sessions/[id]/versions
 * Restore a specific version
 *
 * Body: { versionNumber: number }
 * Returns: { success: true, session: WorkshopSession }
 */
export const POST = withAuth(async (request, { params }) => {
  try {
    const { id } = (await params) as { id: string }
    const userId = await getUserId()
    const body = await request.json()

    const { versionNumber } = body
    if (typeof versionNumber !== 'number') {
      return NextResponse.json({ error: 'versionNumber is required' }, { status: 400 })
    }

    // Verify session ownership
    const session = await db.query.workshopSessions.findFirst({
      where: and(eq(schema.workshopSessions.id, id), eq(schema.workshopSessions.userId, userId)),
    })

    if (!session) {
      return NextResponse.json({ error: 'Session not found' }, { status: 404 })
    }

    // Find the version to restore
    const version = await db.query.flowchartVersionHistory.findFirst({
      where: and(
        eq(schema.flowchartVersionHistory.sessionId, id),
        eq(schema.flowchartVersionHistory.versionNumber, versionNumber)
      ),
    })

    if (!version) {
      return NextResponse.json({ error: 'Version not found' }, { status: 404 })
    }

    // Restore the version by copying its data into the session draft
    const [updatedSession] = await db
      .update(schema.workshopSessions)
      .set({
        draftDefinitionJson: version.definitionJson,
        draftMermaidContent: version.mermaidContent,
        draftTitle: version.title,
        draftDescription: version.description,
        draftEmoji: version.emoji,
        draftDifficulty: version.difficulty as 'Beginner' | 'Intermediate' | 'Advanced' | null,
        draftNotes: version.notes,
        currentVersionNumber: version.versionNumber,
        state: 'refining',
        updatedAt: new Date(),
      })
      .where(eq(schema.workshopSessions.id, id))
      .returning()

    console.log(`[versions] Restored version ${versionNumber} for session ${id}`)

    return NextResponse.json({
      success: true,
      session: updatedSession,
    })
  } catch (error) {
    console.error('Failed to restore version:', error)
    return NextResponse.json({ error: 'Failed to restore version' }, { status: 500 })
  }
})